package com.zqweb.gulimall.product.exception;

import com.zqweb.common.exception.ExpCodeAndMsgEnum;
import com.zqweb.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

// 开启对哪些包下的Controller的Advice切面监控通知，来实现相应的异常处理
@RestControllerAdvice(basePackages = {"com.zqweb.gulimall.product.app"})
@Slf4j
public class GlobalControllerExceptionHandler {
    // 数据校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R dataValidExceptionHandle(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        HashMap<String, String> resMap = new HashMap<>();
        result.getFieldErrors().forEach(error -> {
            resMap.put(error.getField(),error.getDefaultMessage());
        });
        return R.error(ExpCodeAndMsgEnum.DATANOTVALID_EXCEPTION.getCode(),ExpCodeAndMsgEnum.DATANOTVALID_EXCEPTION.getMsg())
                .put("data",resMap);
    }

    // 未知异常
    @ExceptionHandler(value = Throwable.class)
    public R unknownExceptionHandle(Throwable t){
        log.error(t.getMessage());
        return R.error(ExpCodeAndMsgEnum.UNKNOWN_EXCEPTION.getCode(),ExpCodeAndMsgEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
